from flask import Flask, render_template, request, send_file
import os
import json
from bs4 import BeautifulSoup
from bs4 import Tag
from typing import List, Dict, Optional, Any
from flask import Response
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'

def get_templates() -> List[str]:
    """获取所有模板文件列表
    
    Returns:
        List[str]: 返回匹配template*.html模式的文件名列表
    """
    return [f for f in os.listdir('templates') 
           if f.startswith('template') and f.endswith('.html')]

@app.route('/')
def index():
    return render_template('index.html', templates=get_templates())

# 在文件保存前添加文件名安全检查
import re
from werkzeug.utils import secure_filename

def is_allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in {'json', 'txt'}

@app.route('/generate', methods=['POST'])
def generate():
    try:
        template = request.form.get('template')
        if not template:
            return "请选择模板", 400
            
        # 批量转换 - 处理上传的文件
        if 'upload_file' in request.files:
            upload_file = request.files['upload_file']
            if upload_file.filename != '' and is_allowed_file(upload_file.filename):
                return handle_batch_conversion(upload_file, template)
        
        # 单条转换 - 处理表单数据
        return handle_single_conversion(request, template)
    
    except Exception as e:
        return f"处理错误: {str(e)}", 500

def handle_batch_conversion(upload_file, template):
    """处理批量转换（上传文件）"""
    filename = secure_filename(upload_file.filename)
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    upload_file.save(filepath)
    
    if upload_file.filename.endswith('.json'):
        with open(filepath, 'r', encoding='utf-8') as f:
            articles = json.load(f)
    else:  # txt文件
        from message_to_json import convert_message_to_json
        output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'output.json')
        convert_message_to_json(filepath, output_path)
        with open(output_path, 'r', encoding='utf-8') as f:
            articles = json.load(f)
    
    return generate_from_json(articles, template)

def handle_single_conversion(request, template):
    """处理单条转换（表单数据）"""
    article = {
        "title": request.form.get('title'),
        "content": request.form.get('content'),
        "link": request.form.get('link')
    }
    if not all(article.values()):
        return "请填写完整的文章信息", 400
    
    generate_html([article], template)
    return send_file('articles.html', as_attachment=True)

def generate_from_json(articles, template_file):
    generate_html(articles, template_file)
    return send_file('articles.html', as_attachment=True)

# 添加模板缓存
template_cache = {}

def generate_html(articles, template_file):
    if template_file not in template_cache:
        with open(template_file, 'r', encoding='utf-8') as f:
            template_cache[template_file] = BeautifulSoup(f, 'html.parser')
    
    template_soup = template_cache[template_file]
    # 创建基础HTML结构
    html_template = """<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body></body></html>"""
    soup = BeautifulSoup(html_template, 'html.parser')
    body = soup.find('body')
    
    # 为每篇文章创建section
    for i, article in enumerate(articles, 1):
        section = create_article_section(soup, template_soup, i, article)
        body.append(section)
    
    # 保存HTML文件
    with open('articles.html', 'w', encoding='utf-8') as f:
        f.write(soup.prettify())

def create_article_section(soup, template_soup, index, article):
    section = soup.new_tag('section')
    
    # 应用section样式
    template_section = template_soup.find('section')
    if isinstance(template_section, Tag) and template_section.has_attr('style'):
        section['style'] = template_section['style']
    
    # 添加h1标签（序号）
    h1 = create_tag_with_style(soup, template_soup, 'h1', f"{index:02d}")
    section.append(h1)
    
    # 添加h2标签（标题）
    h2 = create_tag_with_style(soup, template_soup, 'h2', article['title'])
    section.append(h2)
    
    # 添加p标签（内容）
    p = create_tag_with_style(soup, template_soup, 'p', article['content'])
    section.append(p)
    
    # 添加a标签（链接）
    a = create_tag_with_style(soup, template_soup, 'a', "阅读原文")
    a['href'] = article['link']
    section.append(a)
    
    return section

def create_tag_with_style(soup, template_soup, tag_name, content):
    tag = soup.new_tag(tag_name)
    template_tag = template_soup.find(tag_name)
    if template_tag and template_tag.has_attr('style'):
        tag['style'] = template_tag['style']
    span = soup.new_tag('span')
    span.string = content
    tag.append(span)
    return tag

# 初始化日志配置
def setup_logging():
    handler = RotatingFileHandler(
        'e:\\html2inline\\app.log',
        maxBytes=1024*1024,
        backupCount=5
    )
    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(message)s'
    )
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.INFO)

if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run('0.0.0.0', 5000, debug=True)